import org.w3c.dom.Node;

import javax.swing.tree.TreeNode;

import java.util.*;

public class BinaryTree {
     static class TreeNode {
         public char val;
         public TreeNode left;
         public TreeNode right;

         public TreeNode(char val) {
             this.val = val;
         }
     }

    //根据前序遍历创建二叉树
    public  int i = 0;
    public  TreeNode createTree(String str) {

        TreeNode root = null;
        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        } else {
            i++;
        }

        return root;
    }

    // 前序遍历
    void preOrder(TreeNode root){
    if(root == null) return;
        System.out.println(root.val);
        preOrder(root.left);
        preOrder(root.right);
    }

    public void preOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    // 中序遍历
    void inOrder(TreeNode root){
        if(root == null) return;
        inOrder(root.left);
        System.out.println(root.val);
        inOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root){
        if(root == null) return;
        inOrder(root.left);
        inOrder(root.right);
        System.out.println(root.val);
    }

    // 获取树中节点的个数
    int size(TreeNode root){
    if(root == null) return 0;

    return size(root.left)
            +size(root.right)+1;
    }

    // 获取叶子节点的个数
    int getLeafNodeCount(TreeNode root){
        if(root == null) return 0;

        if(root.left == null || root.right == null){
            return 1;
        }

        return getLeafNodeCount(root.right)
                +getLeafNodeCount(root.left);
    }

    // 子问题思路-求叶子结点个数
    public static int leafSize;
    public void getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return;
        }

        if(root.left == null && root.right == null) {
            leafSize++;
        }

        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

// 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k){
    if(root == null) return 0;
    if(k == 1) return 1;
    return getKLevelNodeCount(root.left,k-1)
            + getKLevelNodeCount(root.right,k-1);

    }

    // 获取二叉树的高度
    int getHeight(TreeNode root){
        if(root == null) return 0;
        int lefthight = getHeight(root.left);
        int righthight = getHeight(root.right);
        return Math.max(lefthight,righthight)+1;
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, int val){
        if(root == null) return null;

        if(root.val == val){
            return root;
        }

        TreeNode leftT = find(root.left, val);
        if(leftT != null){
            return leftT;
        }

        TreeNode rightT = find(root.right,val);
        if(rightT != null){
            return rightT;
        }

        return null;
    }

    //层序遍历
    void levelOrder(TreeNode root){
        if(root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.println(cur.val);

            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }

    }

    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if(root == null) return ret;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            List<Character> list = new ArrayList<>();

            while(size != 0){

                TreeNode cur = queue.poll();
                list.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }

        return ret;
    }


    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root){
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while(!queue.isEmpty()){
            TreeNode peek = queue.peek();
            if(peek!= null){
                return false;
            }
            queue.poll();
        }
        return true;
    }

    //判断两树相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //判断结构是否一样
        if(p != null && q == null || p == null && q != null)
            return false;
        //两个引用同为null
        if(p == null &&q == null)
            return true;
        //都不为空，判断值是否一样
        if(p.val != q.val){
            return false;
        }
        //都不为空且值一样
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //另一颗树的子树
    //时间复杂度为O（r*s）
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null){
            return false;
        }
        if(isSameTree(root,subRoot)) return true;
        if(isSubtree(root.left,subRoot)) return true;
        if(isSubtree(root.right,subRoot)) return true;

        return false;

    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;

        return isSymmetricChild(root.left,root.right);

    }
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if(leftTree != null && rightTree == null
                || leftTree == null && rightTree != null)
            return false;

        if(leftTree == null && rightTree == null)
            return true;

        if(leftTree.val != rightTree.val){
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }

    //判断一颗二叉树是否是平衡二叉树。
    //时间复杂度为：O(n^2)
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int leftHight = getHeight(root.left);
        int rightHight = getHeight(root.right);
        if(Math.abs(leftHight-rightHight) >= 2){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    //  时间复杂度为：O(n)
    public boolean isBalanced2(TreeNode root) {
        if(root == null) return true;

        return getHeight2(root) >= 0;
    }
    public int getHeight2(TreeNode root){
        if(root == null) return 0;

        int leftHight = getHeight2(root.left);
        if(leftHight < 0){
            return -1;
        }
        int rightHight = getHeight2(root.right);
        if(rightHight < 0){
            return -1;
        }
        if(Math.abs(leftHight-rightHight) <= 1){
            return Math.max(leftHight,rightHight)+1;
        } else {
            return -1;
        }
    }

    //二叉搜索树与双向链表
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) return null;

        ConvertChild(pRootOfTree);
        TreeNode head = pRootOfTree;
        while(head.left != null){
            head = head.left;
        }
        return head;
    }

    TreeNode prev = null;
    public void ConvertChild(TreeNode root) {
        if (root == null) return;

        ConvertChild(root.left);

        //
        root.left = prev;
        if (prev != null) {
            prev.right = root;
        }
        prev = root;

        ConvertChild(root.right);
    }

    //找到一个二叉树中两个指定节点的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;

        if(p == root || q == root){
            return root;
        }

        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);

        if(leftTree != null && rightTree != null){
            return root;
        } else if(leftTree != null){
            return leftTree;
        } else if (rightTree != null){
            return rightTree;
        }

        return null;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        //1.获取路径上的所有节点
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        //2. 比较两个栈的大小，多的出size个
        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if(sizeP > sizeQ) {
            int size = sizeP - sizeQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        }else {
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }
        //3. 每次出数据 看栈顶元素是否一样
        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if (stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            } else {
                stackQ.pop();
                stackP.pop();
            }
        }

        return null;
    }
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        if(root == null) return false;

        stack.push(root);

        if(root == node){
            return true;
        }
        boolean ret = getPath(root.left,node,stack);
        if(ret == true){
            return true;
        }
        ret = getPath(root.right,node,stack);
        if(ret == true){
            return true;
        }
        stack.pop();
        return false;
    }

//根据一棵树的前序遍历与中序遍历构造二叉树
public int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
    public TreeNode buildTreeChild(int[] preorder, int[] inorder ,int inbegin,int inend) {
        if(inbegin > inend){
            //没有子树
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }
    private int findVal(int[] inorder, int inbegin,int inend,int val){
        for(int i = inbegin ;i <= inend ;i++){
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
    public int postIndex;
    public TreeNode buildTree2(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return buildTreeChild(inorder,postorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild2(int[] inorder,int[] postorder,int inbegin,int inend) {
        //这种情况下 表明 当前root 没有子树了
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;

        root.right = buildTreeChild(inorder,postorder,rootIndex+1,inend);

        root.left = buildTreeChild(inorder,postorder,inbegin,rootIndex-1);

        return root;
    }

    //二叉树创建字符串
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }

        StringBuilder stringBuilder = new  StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();

    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) return;
        stringBuilder.append(t.val);//1

        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }

    }
}
